package com.gjj.abox.support;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.gjj.abox.constant.Constants;
import com.gjj.abox.constant.FileTypes;
import com.gjj.abox.database.R;
import com.gjj.abox.entity.FileInfo;
import com.gjj.abox.utils.ToastUtil;

public class FileChooserActivity extends Activity {

    private GridView mGridView;
    private View mBackView;
    private View mBtExit;
    private TextView mTitle;
    private Toast mToast;

    private String mSdcardRootPath;  //sdcard 根路径
    private String mLastFilePath;    //当前显示的路径

    private ArrayList<FileInfo> mFileLists;
    private FileChooserAdapter mAdatper;
    private Button btnComplete;
    private FileInfo fileInfo;
    private String formType;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.filechooser_show);
        mSdcardRootPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        mBackView = findViewById(R.id.imgBackFolder);
        mBackView.setOnClickListener(mClickListener);
        mBtExit = findViewById(R.id.tv_exit);
        mBtExit.setOnClickListener(mClickListener);
        btnComplete = (Button) findViewById(R.id.btn_file_chooser_add);
        mTitle = (TextView) findViewById(R.id.tv_file_chooser_title);

        mGridView = (GridView) findViewById(R.id.gvFileChooser);
        mGridView.setEmptyView(findViewById(R.id.tvEmptyHint));
        mGridView.setOnItemClickListener(mItemClickListener);
        setGridViewAdapter(mSdcardRootPath);
        btnComplete.setOnClickListener(mClickListener);
        getParas();
    }

    //获取传递数据
    private void getParas() {
        formType = getIntent().getStringExtra(Constants.From);
        if (formType!=null && formType.equals(Constants.Choose_File_Package)) {
            btnComplete.setVisibility(View.VISIBLE);
        } else {
            btnComplete.setVisibility(View.GONE);
        }
    }

    //配置适配器
    private void setGridViewAdapter(String filePath) {
        updateFileItems(filePath);
        mAdatper = new FileChooserAdapter(this, mFileLists);
        mGridView.setAdapter(mAdatper);
    }

    //根据路径更新数据，并且通知Adatper数据改变
    @SuppressWarnings("unchecked")
    private void updateFileItems(String filePath) {
        mLastFilePath = filePath;
        String path = (mLastFilePath.split("/"))[(mLastFilePath.split("/")).length - 1];
        mTitle.setText(path);

        if (mFileLists == null)
            mFileLists = new ArrayList<FileInfo>();
        if (!mFileLists.isEmpty())
            mFileLists.clear();

        File[] files = folderScan(filePath);
        if (files == null)
            return;

        for (int i = 0; i < files.length; i++) {
            if (files[i].isHidden())  // 不显示隐藏文件
                continue;

            String fileAbsolutePath = files[i].getAbsolutePath();
            String fileName = files[i].getName();
            double fileSize = files[i].length();
            boolean isDirectory = false;
            if (files[i].isDirectory()) {
                isDirectory = true;
            }

            FileInfo fileInfo = new FileInfo(fileAbsolutePath, fileName, fileSize, isDirectory);
            mFileLists.add(fileInfo);
        }
        FileInfo.ComparatorUser comparator = new FileInfo.ComparatorUser();
        Collections.sort(mFileLists, comparator);  //排序
        //When first enter , the object of mAdatper don't initialized
        if (mAdatper != null)
            mAdatper.notifyDataSetChanged();  //重新刷新
    }

    //获得当前路径的所有文件
    private File[] folderScan(String path) {
        File file = new File(path);
        File[] files = file.listFiles();
        return files;
    }

    private OnClickListener mClickListener = new OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.imgBackFolder:
                    backProcess();
                    break;
                case R.id.tv_exit:
                    setResult(RESULT_CANCELED);
                    finish();
                    break;
                case R.id.btn_file_chooser_add:
                    Intent intent = new Intent();
                    if(fileInfo != null){
                        intent.putExtra("file_chooser", mLastFilePath);
                        setResult(RESULT_OK, intent);
                        finish();
                    }else{
                        ToastUtil.showShortToast(FileChooserActivity.this,"请选择文件夹");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private OnItemClickListener mItemClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapterView, View view, int position,
                                long id) {
            fileInfo = (FileInfo) (((FileChooserAdapter) adapterView.getAdapter()).getItem(position));
            if (fileInfo.isDirectory())   //点击项为文件夹, 显示该文件夹下所有文件
                updateFileItems(fileInfo.getFilePath());
            else {
//			    Intent intent = new Intent();
//			    intent.putExtra("file_chooser" , fileInfo.getFilePath());
//			    setResult(RESULT_OK , intent);
//			    finish();
//				String size = "";
                if(formType != null && formType.equals(Constants.Choose_File_Package)){
                    return;
                }
                if (fileInfo.getFileType(fileInfo.getFileName()).equals(FileTypes.DB_SUFFIX)) {
                    showToast("文件格式不支持！");
                }
//				else if(fileInfo.getFileSize()>(1024*1024*10)){
//					showToast("文件大于 10MB!");
//				}else{
//					Intent intent = new Intent();
//				    intent.putExtra("file_chooser", fileInfo.getFilePath());
//				    setResult(RESULT_OK , intent);
//				    finish();
//				}
//				if(fileInfo.getFileSize()<1024*1024){
//					size = new BigDecimal(fileInfo.getFileSize()/1024).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue()+"KB";
//				}
//				else if(1048576*1024>fileInfo.getFileSize()&&fileInfo.getFileSize()>1048576){
//					size = new BigDecimal(fileInfo.getFileSize()/1048576).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue()+"MB";
//				}else {
//					size = new BigDecimal(fileInfo.getFileSize()/(1048576*1024)).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue()+"GB";
//				}
//				Toast.makeText(getApplicationContext(), "大小："+size+","+fileInfo.getFileType(fileInfo.getFileName()),Toast.LENGTH_LONG).show();
                if (fileInfo.isDBFile()) {
                    Intent intent = new Intent();
                    intent.putExtra("file_chooser", fileInfo.getFilePath());
                    intent.putExtra("file_name", fileInfo.getFileName());
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    showToast("文件格式不支持！");
                }
            }
        }
    };

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode()
                == KeyEvent.KEYCODE_BACK) {
            backProcess();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //返回上一层目录的操作
    public void backProcess() {
        //判断当前路径是不是sdcard路径 ， 如果不是，则返回到上一层。
        if (!mLastFilePath.equals(mSdcardRootPath)) {
            File thisFile = new File(mLastFilePath);
            String parentFilePath = thisFile.getParent();
            updateFileItems(parentFilePath);
        } else {   //是sdcard路径 ，直接结束
            setResult(RESULT_CANCELED);
            finish();
        }
    }

    public void showToast(String text) {
        if (mToast == null) {
            mToast = Toast.makeText(getApplicationContext(), text,
                    Toast.LENGTH_SHORT);
        } else {
            mToast.setText(text);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }
}